#include <QtGui/QApplication>
#include <QtXmlPatterns/QXmlQuery>
#include "mainwindow.h"
#include <QSqlError>
#include "DbConnection.h"
#include "ConnectDialog.h"
#include <QSplashScreen>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);   
    QTextCodec::setCodecForTr(QTextCodec::codecForName("utf-8"));
    QTextCodec::setCodecForLocale(QTextCodec::codecForName("utf-8"));
    QSplashScreen* screen = new QSplashScreen(QPixmap(":/start_screen"));
    QFont curr_font=screen->font();
    curr_font.setPointSize(9);
    screen->setFont(curr_font);
    screen->showMessage(QObject::tr("Чтение файла конфигурации..."),Qt::AlignBottom);
    screen->show();
    QString FileConfigName=a.applicationFilePath();
    FileConfigName = FileConfigName.replace(QRegExp("[\\w+-]+\\.exe"),"config.xml");
    QList<unit> units;
    QString capTitle="AWSD";
    if(!QFile::exists(FileConfigName))
    {
        screen->showMessage(QObject::tr("Аварийное завершение: файл конфигурации не найден."),Qt::AlignBottom,Qt::red);
        QTime time;
        time.start();
        for(;time.elapsed() < 3000;){}
        return 0;
    }
    else
    {
        QFile file(FileConfigName);
        if(file.open(QIODevice::ReadOnly|QIODevice::Text))
        {
            QTextStream in(&file);
            QString xml;
            while(!in.atEnd()) xml.append(in.readLine()+"\n");
            file.close();
            QXmlQuery q;
            QString res;
            q.setFocus(xml);
            q.setQuery("/settings/states/element[@name=\"MainWindow\"]/capTitle/@value/string()");
            if(q.evaluateTo(&res))
            {
                res=res.replace("\n","");
                capTitle=res;
            }
            q.setQuery("/settings/units/unit/@name/string()");            
            q.evaluateTo(&res);
            res=res.replace("\n","");
            foreach(QString name, res.split(" "))
            {
                unit tmp;
                tmp.name=name;
                QString str;
                q.setQuery(QObject::tr("/settings/units/unit[@name=\"%1\"]/host/string()").arg(name));
                if(q.evaluateTo(&str))
                {
                    str=str.replace("\n","");
                    tmp.params.host=str;
                }
                q.setQuery(QObject::tr("/settings/units/unit[@name=\"%1\"]/port/string()").arg(name));
                if(q.evaluateTo(&str))
                {
                    str=str.replace("\n","");
                    tmp.params.port=str.toInt();
                }
                q.setQuery(QObject::tr("/settings/units/unit[@name=\"%1\"]/driver/string()").arg(name));
                if(q.evaluateTo(&str))
                {
                    str=str.replace("\n","");
                    tmp.params.driver=str;
                }
                q.setQuery(QObject::tr("/settings/units/unit[@name=\"%1\"]/dataBase/string()").arg(name));
                if(q.evaluateTo(&str))
                {
                    str=str.replace("\n","");
                    tmp.params.DbName=str;
                }
                q.setQuery(QObject::tr("/settings/units/unit[@name=\"%1\"]/schema/string()").arg(name));
                if(q.evaluateTo(&str))
                {
                    str=str.replace("\n","");
                    tmp.params.schema=str;
                }
                q.setQuery(QObject::tr("/settings/units/unit[@name=\"%1\"]/user/@name/string()").arg(name));
                if(q.evaluateTo(&str))
                {
                    str=str.replace("\n","");
                    tmp.users=str.split("; ");
                }
                units.append(tmp);
            }
        }
    }
    ConnectDialog dialog(0,units);
    while(1)
    {
        screen->showMessage(QObject::tr("Авторизация..."),Qt::AlignBottom);
        dialog.exec();
        if(dialog.result()==QDialog::Rejected)
        {
            delete screen;
            return 0;
        }
        screen->showMessage(QObject::tr("Подключение к системе..."),Qt::AlignBottom);
        if(dialog.login())
        {
            screen->showMessage(QObject::tr("Подключение установлено..."),Qt::AlignBottom);
            DbConnection::QueryResult res = dialog.db()->execute(QObject::tr("select =schema=.ex_access()"));            
            if(res.success()&&res.at(0,0).toBool())
            {
                MainWindow window(FileConfigName,dialog.db(),0);
                QObject::connect(&window,SIGNAL(init_message(QString,int,QColor)),
                                  screen,SLOT(showMessage(QString,int,QColor)));
                if(window.initialization())
                {

                    screen->finish(&window);
                    window.show();
                    window.setWindowIcon(QIcon(":/test"));
                    delete screen;
                    return a.exec();
                }
                QTime time;
                time.start();
                for(;time.elapsed() < 3000;){}
                return 0;
             }
             QMessageBox::warning(0,QObject::tr("Доступ запрещен"),
                                    QObject::tr("Учетная запись не имеет достаточных прав."),1,0);
         }
         else
         {
            QString err=QObject::tr("Сервер баз данных недоступен.");
            QRegExp rx(".*password authentication.*");
            if(rx.exactMatch(dialog.db()->lastError().text()))
            {
               err=QObject::tr("Неверное имя пользователя или пароль.");
            }
            else
            {
               rx.setPattern(".*role.*does not exist.*");
               if(rx.exactMatch(dialog.db()->lastError().text())) err=QObject::tr("Учетная запись не найдена.");
            }
            QMessageBox::warning(0,QObject::tr("Ошибка подключения"),err,1,0);
         }
     }
}
